<template>
    <el-form :model="addSpuData" label-width="130px" class="demo-ruleForm" status-icon>
        <el-form-item label="SPU名称">
            <el-input v-model="addSpuData.spuName" />
        </el-form-item>
        <el-form-item label="SPU品牌" prop="region">
            <el-select v-model="addSpuData.tmId">
                <el-option v-for="item in spuPpData" :key="item.id" :label="item.tmName" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" v-model="addSpuData.description" />
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImgData" :action="API.UP_FILE" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :before-upload="beforeAvatarUpload">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full style="width: 100%;height: 100%;" :src="dialogImageUrl" />
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性" prop="region">
            <el-select v-model="spuValue" :placeholder="unSpuAttr.length ? `还未选择${unSpuAttr.length}个` : '无'">
                <el-option v-for="item in unSpuAttr" :key="item.id" :label="item.name" :value="item.id + ':' + item.name" />
            </el-select>
            <el-button :disabled="spuValue ? false : true" @click="addAttrClick" type="primary" icon="Plus"
                style="margin-left:15px">添加属性</el-button>
        </el-form-item>
        <el-form-item label="" prop="region">
            <el-table :data="spuAttrData" border style="width: 100%">
                <el-table-column type="index" label="序号" width="90" />
                <el-table-column prop="saleAttrName" label="销售属性名字" width="180" />
                <el-table-column label="销售属性值">
                    <template #="{ row }">
                        <el-tag @close="row.spuSaleAttrValueList.splice(i, 1)" v-for="(tag, i) in row.spuSaleAttrValueList"
                            :key="tag.id" class="mx-1" closable> {{
                                tag.saleAttrValueName
                            }}
                        </el-tag>
                        <el-input @blur="toSee(row)" style="width: 100px;" v-if="row.show" v-model="row.attrName"
                            placeholder="请输入你的属性值"></el-input>
                        <el-button v-else @click="toEdit(row)" type="primary" size="small" icon="Plus"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{ $index }">
                        <el-button type="primary" @click="spuAttrData.splice($index, 1)" icon="Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label="" prop="region">
            <el-button type="primary" @click="addTrueSpu">保存</el-button>
            <el-button type="primary" @click="outAddSup">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import {
    getTrademarkList, getSpuImageList,
    getSpuSaleAttrList, getBaseSaleAttrList, addOrUpdataSpu
} from '@/api/product/spu';
import type {
    ReturnPpList, PpData, ReturnAllAttr,
    SpuValue, SorN, ReturnImages,
    ImgData, ReturnAttr, SpuAttr, Attr
} from '@/api/product/spu/type';
import { API } from '@/api/product/trademark/index'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'

const $emit = defineEmits(['changeFlagCard'])
const outAddSup = () => {
    $emit('changeFlagCard', { flagCard: 0, pageNo: 1 })
}
// 搜集数据
const addSpuData = reactive<SpuValue>({
    category3Id: '',
    description: '',
    spuImageList: [],
    spuName: '',
    spuPosterList: [],
    spuSaleAttrList: [],
    tmId: ''
})
// 品牌
const spuPpData = ref<PpData[]>([])
// 图片预览弹出
const spuImgData = ref<ImgData[]>([])
// 已有属性
const spuAttrData = ref<SpuAttr[]>([])
// 图片预览弹出
const dialogVisible = ref<boolean>(false)
// 图片地址
const dialogImageUrl = ref<string>('')
// 所有属性
const allAttr = ref<Attr[]>([])
// 选择属性值得id名称
const spuValue = ref<string>('')

// 对外暴露的方法
const info = (row: SpuValue) => {
    getSpuPp()
    getAllAtr()
    getSpuImg((row.id as string))
    getSpuAttr((row.id as string))
    Object.assign(addSpuData, row)
}
// 计算属性
const unSpuAttr = computed(() => {
    let arr = allAttr.value.filter(item => {
        return spuAttrData.value.every(sub => {
            return item.name != sub.saleAttrName
        })
    })
    return arr
})
// 获取spu品牌
const getSpuPp = async () => {
    const data: ReturnPpList = await getTrademarkList()
    if (data.code === 200) spuPpData.value = data.data
}
// 获取照片墙
const getSpuImg = async (spuId: SorN) => {
    const data: ReturnImages = await getSpuImageList(spuId)
    if (data.code === 200) {
        spuImgData.value = data.data.map(item => {
            return {
                name: item.imgName,
                url: item.imgUrl
            }
        })
    }
}
// 获取所有属性
const getAllAtr = async () => {
    const data: ReturnAllAttr = await getBaseSaleAttrList()
    if (data.code === 200) allAttr.value = data.data
}
// 获取已有属性
const getSpuAttr = async (spuId: SorN) => {
    const data: ReturnAttr = await getSpuSaleAttrList(spuId)
    if (data.code === 200) {
        spuAttrData.value = data.data
    }


}
// 点击图片
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogVisible.value = true
    dialogImageUrl.value = uploadFile.url!

}
// 上传之前的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
    if (file.type == 'image/jpeg' || file.type == 'image/gif' || file.type == 'image/png') {
        if (file.size / 1024 / 1024 < 4) {
            return true
        } else {
            ElMessage.error('上传文件务必小于3M!')
            return false

        }
    } else {
        ElMessage.error('上传文件务必PNG|JPG|GIF！')
        return false

    }
}
// 添加属性值、
const addAttrClick = () => {
    const [baseSaleAttrId, saleAttrName] = spuValue.value.split(':')
    spuAttrData.value.push(
        {
            baseSaleAttrId,
            saleAttrName,
            spuSaleAttrValueList: []
        }
    )
    spuValue.value = ''
}
// 添加属性值
const toEdit = (row: SpuAttr) => {
    row.show = true
    row.attrName = ''
}
// 查看添加
const toSee = (row: SpuAttr) => {
    const { baseSaleAttrId } = row
    if (row.attrName?.trim() == '') {
        ElMessage.error('请输入属性值')
        return false
    }
    let index = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName == row.attrName
    })
    if (index) {
        ElMessage.error('不能输入重复的值')
        return false
    }
    row.spuSaleAttrValueList.push({
        baseSaleAttrId,
        saleAttrValueName: (row.attrName as string)
    })
    row.show = false

}
// 确定添加
const addTrueSpu = async () => {
    addSpuData.spuImageList = spuImgData.value.map((item: any) => {
        return {
            imgName: (item.name as string),
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    addSpuData.spuSaleAttrList = spuAttrData.value
    let res: any = await addOrUpdataSpu(addSpuData)
    if (res.code == 200) {
        ElMessage.success(addSpuData.id ? '修改成功' : '添加成功')
        $emit('changeFlagCard', { flagCard: 0, pageNo: 2 })
    } else {
        ElMessage.error(addSpuData.id ? '修改失败' : '添加失败')
    }
}
// 新增spu
const newSpu = (C3Id: number) => {
    Object.assign(addSpuData, {
        category3Id: '',
        description: '',
        spuImageList: [],
        spuName: '',
        spuPosterList: [],
        spuSaleAttrList: [],
        tmId: ''
    })
    spuAttrData.value = []
    spuImgData.value = []
    getSpuPp()
    getAllAtr()
    addSpuData.category3Id = C3Id

}
// 对外进行暴露
defineExpose({ info, newSpu })


</script>
<script lang="ts">
export default {
    name: 'AddSpu'
}
</script>
<style scoped lang="scss">
.el-tag {
    margin: 0 5px;
}
</style>